﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UIGen
{
  class TGenerator
  {
    private static string OutputDir;
    private static string Extension;
    private static string Namespace;
    private static string TabSymbol;
    private static string LineBreak;

    enum NodeTypes
    {
      DataObject,
      DataField,
    }

    enum Attributes
    {
      CodeName,
      UserName,
      FieldType,
    }

    private static string InputType(string FieldType)
    {
      return "text";
    }

    private static string InputClass(string FieldType)
    {
      return "";
    }

    private static string FormatString(string Input)
    {
      return Input.Replace("\t", TabSymbol).Replace("\n", LineBreak);
    }

    private TGenerator(System.Xml.Linq.XElement Node)
    {
      System.Diagnostics.Debug.Assert(Node != null);
      System.Diagnostics.Debug.Assert(Node.Name == NodeTypes.DataObject.ToString());

      StringBuilder Builder = new StringBuilder();
      Builder.Append(string.Format(
          "<div>\n\t<div>\n\t\t{0}\n\t</div>\n\n",
          Node.Attribute(Attributes.UserName.ToString()).Value
        ));
      foreach (var elem in Node.Elements(NodeTypes.DataField.ToString()))
      {
        Builder.Append(string.Format(
            "\t<div>\n\t\t{0}\n\t\t<input type=\"{1}\" id=\"{2}\" class=\"{3}\"/>\n\t</div>\n\n",
            elem.Attribute(Attributes.UserName.ToString()).Value,
            InputType(elem.Attribute(Attributes.FieldType.ToString()).Value),
            elem.Attribute(Attributes.CodeName.ToString()).Value,
            InputClass(elem.Attribute(Attributes.FieldType.ToString()).Value)
          ));

      }
      Builder.Append("</div");

      string FileName = OutputDir + "\\" + Node.Attribute(Attributes.CodeName.ToString()).Value + "." + Extension;
      using (System.IO.StreamWriter Writer = new System.IO.StreamWriter(FileName))
        Writer.Write(FormatString(Builder.ToString()));

      foreach (var elem in Node.Elements(NodeTypes.DataObject.ToString()))
        new TGenerator(elem);
    }

    static void Main(string[] args)
    {
      #region Check user input
      if (args.Count() < 2)
      {
        Console.WriteLine("usage: {0} config.file output",
          System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
        return;
      }
      #endregion

      #region Configure output
      TGenerator.OutputDir = args[1];
      TGenerator.Extension = "html";
      TGenerator.TabSymbol = "  ";
      TGenerator.LineBreak = "\r\n";
      #endregion

      System.Xml.Linq.XElement Config = System.Xml.Linq.XElement.Load(args[0]);
      new TGenerator(Config);
    }
  }
}
